package cn.doctor.assistant.pad.ui.ziliao;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.doctor.assistant.pad.MyApplication;
import cn.doctor.assistant.pad.R;
import cn.doctor.assistant.pad.api.ziliao.AddRecordRequest;
import cn.doctor.assistant.pad.api.ziliao.InformatApi;
import cn.doctor.assistant.pad.base.BaseNetActivity;
import cn.doctor.assistant.pad.base.ResultCallback;
import cn.doctor.assistant.pad.entity.AssUser;
import cn.doctor.assistant.pad.entity.Dept;
import cn.doctor.assistant.pad.entity.Doctor;
import cn.doctor.assistant.pad.entity.Patient;
import cn.doctor.assistant.pad.entity.Record;
import cn.doctor.assistant.pad.ui.SpinnerHelper;
import cn.doctor.assistant.pad.ui.UI;

/**
 * Created by jiaolf on 2016/4/1.
 * 新增住院记录
 */
public class AddZhuYuanActivity extends BaseNetActivity {

    String[] doctorItems;
    String[] keshiItems;
    String[] patientFroms = {"朋友推荐", "网络搜索", "其他"};

    @InjectView(R.id.titlebar_left_title)
    TextView titlebarLeftTitle;
    @InjectView(R.id.titlebar_right_text)
    TextView titlebarRightText;
    @InjectView(R.id.icon)
    ImageView icon;
    @InjectView(R.id.text_name)
    TextView textName;
    @InjectView(R.id.spinner_keshi)
    Spinner spinnerKeshi;
    @InjectView(R.id.edit_zhenduan)
    EditText editZhenduan;
    @InjectView(R.id.edit_ruyuan_date)
    EditText editRuyuanDate;
    @InjectView(R.id.edit_zhuyuanhao)
    EditText editZhuyuanhao;
    @InjectView(R.id.spinner_doctor)
    Spinner spinnerDoctor;
    @InjectView(R.id.edit_chuyuan_date)
    EditText editChuyuanDate;
    @InjectView(R.id.spinner_patient_from)
    Spinner spinnerPatientFrom;

    Patient patient;
    List<Dept> deptList;
    Map<Integer, List<Doctor>> mDoctors = new HashMap<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_zhuyuan);
        ButterKnife.inject(this);
        setTitle("新增住院记录");
        setRightTitleBarText("保存");

        patient = (Patient) getIntent().getExtras().getSerializable("patient");
        initialize();
    }

    void initialize() {
        SpinnerHelper.init(spinnerPatientFrom, patientFroms, null);
        textName.setText(patient.getName());
        getDept();

        editRuyuanDate.setFocusableInTouchMode(false);
        editChuyuanDate.setFocusableInTouchMode(false);
    }

    void getDept() {
        InformatApi.getDeptList(new ResultCallback<List<Dept>>() {
            @Override
            public void onSuccess(List<Dept> result) {
                if (result.size() > 0) {
                    deptList = result;
                    keshiItems = new String[result.size()];
                    for (int i = 0; i < result.size(); i++) {
                        keshiItems[i] = result.get(i).getName();
                    }

                    SpinnerHelper.init(spinnerKeshi, keshiItems, new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            if (mDoctors.containsKey(deptList.get(position).getId())) {
                                return;
                            } else {
                                getDoctors();
                            }
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    });
                }
            }
        });
    }

    ArrayAdapter<String> adapter;

    void setDoctorSpinnerAdapter() {
        if (adapter == null) {
            adapter = new ArrayAdapter<>(this,
                    android.R.layout.simple_spinner_item, doctorItems);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerDoctor.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    void getDoctors() {
        final int deptId = deptList.get(spinnerKeshi.getSelectedItemPosition()).getId();
        InformatApi.getDoctorList(deptId, new ResultCallback<List<Doctor>>() {
            @Override
            public void onSuccess(List<Doctor> result) {
                if (result.size() > 0) {
                    mDoctors.put(deptId, result);
                    doctorItems = new String[result.size()];
                    for (int i = 0; i < result.size(); i++) {
                        doctorItems[i] = result.get(i).getName();
                    }
                    setDoctorSpinnerAdapter();
                }
            }
        });
    }


    private void save() {
        AssUser assistant = MyApplication.getInstance().mAssistUser;
        final AddRecordRequest recordRequest = new AddRecordRequest();
        recordRequest.setPatient_id(patient.getId());
        recordRequest.setDept_name(deptList.get(spinnerKeshi.getSelectedItemPosition()).getName());
        int deptId = deptList.get(spinnerKeshi.getSelectedItemPosition()).getId();
        recordRequest.setDept_id(deptId);
        Doctor doctor = mDoctors.get(deptId).get(spinnerDoctor.getSelectedItemPosition());
        recordRequest.setMajor_name(doctor.getName());
        recordRequest.setMajor_id(doctor.getId());
        recordRequest.setAid_name(assistant.getReal_name());
        recordRequest.setAid_id(Integer.valueOf(assistant.getId()));
        String note = editZhenduan.getText().toString();
        recordRequest.setNote(note);

        recordRequest.setAdmission_date(ruyuanDate);

        recordRequest.setDischarge_date(chuyuanDate);
        recordRequest.setInhiscode(editZhuyuanhao.getText().toString());
        recordRequest.setOrigin(patientFroms[spinnerPatientFrom.getSelectedItemPosition()]);

        InformatApi.addRecord(recordRequest, new ResultCallback<String>() {
            @Override
            public void onSuccess(String result) {
                UI.showToast("保存成功");

                Intent intent = new Intent();
                Record record =  new Record();
                record.setDept(recordRequest.getDept_name());
                record.setNote(recordRequest.getNote());
                record.setAdmissionDate(ruyuanDateStr + " 00:00:00");
                if (!TextUtils.isEmpty(chuyuanDate)) {
                    record.setDischargeDate(chuyuanDateStr + " 00:00:00");
                }
                intent.putExtra("record", record);
                setResult(RESULT_OK, intent);

                titlebarRightText.setVisibility(View.GONE);
                spinnerKeshi.setEnabled(false);
                spinnerDoctor.setEnabled(false);
                editZhenduan.setEnabled(false);
                editRuyuanDate.setEnabled(false);
                editChuyuanDate.setEnabled(false);
                editZhuyuanhao.setEnabled(false);
                spinnerPatientFrom.setEnabled(false);
            }
        });
    }

    String ruyuanDateStr;
    String ruyuanDate; // 格式 "Apr 1, 2016 3:01:24 PM"

    void setAdmissionDate() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int monthOfYear = calendar.get(Calendar.MONTH);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH) + 1;

        new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                ruyuanDateStr = String.format("%s-%02d-%02d", year, monthOfYear + 1, dayOfMonth);
                editRuyuanDate.setText(ruyuanDateStr);

                Date date = new Date();
                date.setYear(year - 1900);
                date.setMonth(monthOfYear);
                date.setDate(dayOfMonth);
                ruyuanDate = String.format(Locale.US, "%tb %d, %d 00:00:00", date, dayOfMonth, year);
                //UI.showToast(ruyuanDate);

            }

        }, year, monthOfYear, dayOfMonth).show();
    }

    String chuyuanDateStr;
    String chuyuanDate; // 格式 "Apr 1, 2016 3:01:24 PM"

    void setDischargeDate() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int monthOfYear = calendar.get(Calendar.MONTH);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH) + 1;

        new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                chuyuanDateStr = String.format("%s-%02d-%02d", year, monthOfYear + 1, dayOfMonth);
                editChuyuanDate.setText(chuyuanDateStr);

                Date date = new Date();
                date.setYear(year - 1900);
                date.setMonth(monthOfYear);
                date.setDate(dayOfMonth);
                chuyuanDate = String.format(Locale.US, "%tb %d, %d 00:00:00", date, dayOfMonth, year);
                //UI.showToast(chuyuanDate);

            }

        }, year, monthOfYear, dayOfMonth).show();
    }

    @OnClick({R.id.titlebar_left_title, R.id.titlebar_right_text, R.id.edit_ruyuan_date, R.id.edit_chuyuan_date})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.titlebar_left_title:
                back();
                break;
            case R.id.titlebar_right_text:
                save();
                break;
            case R.id.edit_ruyuan_date:
                setAdmissionDate();
                break;
            case R.id.edit_chuyuan_date:
                setDischargeDate();
                break;
        }
    }
}
